<template>
  <div v-if="isAdd == 1" class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="search">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px">
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入商品名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="商品分类" prop="cateId">
            <el-tree-select
              v-model="queryParams.cateId"
              :data="assetCategoryOptions"
              :props="{ value: 'id', label: 'name', children: 'children' }"
              value-key="id"
              filterable
              :render-after-expand="false"
            />
          </el-form-item>
          <el-form-item label="所属仓库" prop="warehouseId">
            <el-input v-model="queryParams.warehouseId" placeholder="请输入所属仓库" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card v-if="isAdd == 1" shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['erp:products:add']" type="primary" plain icon="Plus" @click="handleAdd">新增 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['erp:products:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['erp:products:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['erp:products:export']" type="warning" plain icon="Download" @click="handleExport"> 导出 </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="productsList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" type="index" width="80" />
        <el-table-column label="商品分类" align="center" prop="cateName" />
        <el-table-column label="商品名称" align="center" prop="name" />
        <el-table-column label="图片" align="center" prop="imgUrl" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.imgUrl" :width="30" :height="30" />
          </template>
        </el-table-column>
        <el-table-column label="默认单价" align="center" prop="price" />
        <el-table-column label="库存数量" align="center" prop="stock" />
        <el-table-column label="最新进价" align="center" prop="newPrice" />
        <el-table-column label="库存价" align="center" prop="oldPrice" />
        <el-table-column label="包装单位" align="center" prop="unitId">
          <template #default="scope">
            <span class="show-unit">{{ scope.row.unitName }}</span>
            <el-button class="show-attr" @click="addAttr(scope.row)">查看规格</el-button>
          </template>
        </el-table-column>
        <el-table-column label="产品状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="sys_show_hide" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="所属仓库" align="center" prop="warehouseId" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['erp:products:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['erp:products:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改多计量管理对话框 -->
    <UnitAttrDialog v-if="dialog.visible" v-model="dialog.visible" :form-data="formData" :title="dialog.title" width="500px" append-to-body />
  </div>
  <!-- 新增/编辑 -->
  <AddPage v-if="isAdd == 2" :row-data="rowData" @close-add="closeAdd" @get-list="getList" />
</template>

<script setup name="Products" lang="ts">
import { listProducts, getProducts, delProducts } from '@/api/erp/products';
import { ProductsVO } from '@/api/erp/products/types';
import AddPage from '@/views/erp/products/AddPage.vue';
import { listAssetCategory } from '@/api/erp/assetCategory';
import UnitAttrDialog from '@/views/erp/products/unitAttrDialog.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_show_hide } = toRefs<any>(proxy?.useDict('sys_show_hide'));
const productsList = ref<ProductsVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const isAdd = ref<number>(1);
const queryFormRef = ref<ElFormInstance>();
const rowData = ref({});
const assetCategoryOptions = ref<AssetCategoryOption[]>([]);
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
let formData = reactive<any>({});
type AssetCategoryOption = {
  id: number;
  name: string;
  children?: AssetCategoryOption[];
};

const data = reactive<any>({
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    name: undefined,
    cateId: undefined,
    warehouseId: undefined,
    params: {}
  }
});

const { queryParams } = toRefs(data);
/** 查询资产分类下拉树结构 */
const getTreeselect = async () => {
  const res = await listAssetCategory();
  assetCategoryOptions.value = [];
  const data: AssetCategoryOption = { id: 0, name: '顶级节点', children: [] };
  data.children = proxy?.handleTree<AssetCategoryOption>(res.data, 'id', 'parentId');
  assetCategoryOptions.value.push(data);
};
/** 查询商品管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listProducts(queryParams.value);
  productsList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/*添加多计量单位*/
const addAttr = (row) => {
  formData = row;
  dialog.visible = true;
  dialog.title = '添加多计量单位';
};
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ProductsVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  // reset();
  isAdd.value = 2;
};
/*关闭新增*/
const closeAdd = (e) => {
  isAdd.value = e;
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ProductsVO) => {
  // reset();
  isAdd.value = 2;
  const res = await getProducts(row.id);
  rowData.value = res.data;
};

/** 删除按钮操作 */
const handleDelete = async (row?: ProductsVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除商品管理编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delProducts(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'erp/products/export',
    {
      ...queryParams.value
    },
    `products_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
  getTreeselect();
});
</script>

<style lang="scss" scoped>
.show-unit {
  display: block;
}

.show-attr {
  display: none;
}

.el-table__body tr:hover > td .show-attr {
  display: block;
}

.el-table__body tr:hover > td .show-unit {
  display: none;
}
</style>
